<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/7
 * Time: 1:51
 */

namespace app\api\controller\v2;

use app\common\cachemodel\MiniAppUser;
use app\common\cachemodel\Wechat;
use think\Db;
use think\Request;
use XznsTools\cache\CacheManage;

/**绑定微信和解绑微信等接口
 * @title
 * @desc
 * @url
 * @version 1.3.0
 * Class Bind
 * @package app\api\controller\v2
 */
class Bind extends Auth
{
    protected $restActionList = ['index', 'read', 'save', 'update', 'delete'];
    const ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    const GET_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo';
    private $appid;
    private $appsecret;

    public function _initialize()
    {
        parent::_initialize();
        $this->appid = config('wechat.wechat_appid');
        $this->appsecret = config('wechat.wechat_appsecret');
    }

    /**
     * @title
     * @method post
     * @desc    绑定微信
     * @return array
     */
    public function bind_wechat()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $code = input('code', '');

        // 判断是否有code参数(android)
        if (trim($code) == '')
        {
//            获取ios用户信息
            $user_info_json = input('userinfo');
            if ($user_info_json)
            {
                $user_info = json_decode($user_info_json, true);
                if (
                    !isset($user_info['nickname'])
                    || !isset($user_info['sex'])
                    || !isset($user_info['city'])
                    || !isset($user_info['province'])
                    || !isset($user_info['country'])
                    || !isset($user_info['headimgurl'])
                    || !isset($user_info['openid'])
                    || !isset($user_info['unionid'])
                ) return show(config('code.error'), '用户信息错误');
            } else
            {
                return show(config('code.error'), '用户信息错误');
            }
            $access_token = [
                'access_token' => '',
                'refresh_token' => '',
                'expires_in' => 0,
                'scope' => '',
            ];
        } else
        {
            // 获取android用户信息
            $access_token_url = self::ACCESS_TOKEN_URL . "?appid=$this->appid&secret=$this->appsecret&code=$code&grant_type=authorization_code";
            $access_token = json_decode($this->curl_get($access_token_url), true);
            if (isset($access_token['errcode'])) return show(config('code.error'), $access_token['errcode'] . $access_token['errmsg'], [], 403);
            $userinfo_url = self::GET_USERINFO_URL . "?access_token=$access_token[access_token]&openid=$access_token[openid]&lang=zh_CN";
            $user_info = json_decode($this->curl_get($userinfo_url), true);
        }

        if (isset($user_info['errcode'])) return show(config('code.error'), $user_info['errmsg']);

        // 判断是否已经注册微信
        $user = Db::table('app_wechat')
            ->alias('w')
            ->field('u.id,w.nickname,u.avatar,u.forbidden,u.email,u.is_first_login,u.uc_id,u.sex,u.has_self_recode')
            ->join('app_user u', 'u.id=w.uid', 'INNER')
            ->where(['unionid' => $user_info['unionid']])
            ->find();

        $time = time();
//        未注册微信
        if (empty($user))
        {
            //用户表绑定微信名称
            Db::table('app_user')->where('id', $this->user['id'])->update(['nickname' => $user_info['nickname']]);
            // 将微信信息存入微信表
            $wechat = [
                'uid' => $this->user['id'],
                'nickname' => $user_info['nickname'],
                'sex' => $user_info['sex'],
                'city' => $user_info['city'],
                'province' => $user_info['province'],
                'country' => $user_info['country'],
                'headimgurl' => $user_info['headimgurl'],
                'openid' => $user_info['openid'],
                'unionid' => $user_info['unionid'],
                'create_time' => $time,
                'update_time' => $time,
                'access_token' => $access_token['access_token'],
                'refresh_token' => $access_token['refresh_token'],
                'expires_in' => $access_token['expires_in'] + $time,
                'scope' => $access_token['scope'],
            ];

            // 小程序绑定
            $miniUsers = (new MiniAppUser())->where(['unionid' => $user_info['unionid'], 'status' => 0, 'mini_type' => 'WEAPP'])->column('id');
            if ($miniUsers)
            {
                // 更新数据库状态
                (new MiniAppUser())->where(['unionid' => $user_info['unionid'], 'status' => 0, 'mini_type' => 'WEAPP'])->update(['uid' => $this->user['id']]);
                // 删除缓存
                foreach ($miniUsers as $mid)
                {
                    CacheManage::getInstance()->setCacheConfig('miniapp.user', $mid)->rmCache();
                }
            }

            Db::table('app_wechat')->insertGetId($wechat);// 微信账号记录
            $nickname['nickname'] = $user_info['nickname'];

            return show(200, '绑定成功', $nickname);
        }

        return show(config('code.error'), '该微信已被其他账号绑定');
    }

    /**
     * 发起GET请求
     * @param string $url
     * @return mixed
     */
    protected function curl_get($url = '')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    /**
     * @title  解绑微信
     * @method DELETE
     * @desc
     * @return array
     */
    public function unbind_wechat()
    {
        if (!request()->isDelete())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        try
        {
            $tel = Db::table('app_user')->where('id', $this->user['id'])->field('tel')->find();
            if (isset($tel['tel']) && $tel)
            {
                Db::table('app_user')->where('id', $this->user['id'])->update(['nickname' => '']);
//                Db::table('app_wechat')->where('uid', $this->user['id'])->delete();
                (new Wechat())->DelData($this->user['id']);

                // 小程序解绑
                $miniUsers = (new MiniAppUser())->where(['uid' => $this->user['id'], 'status' => 0, 'mini_type' => 'WEAPP'])->column('id');
                if ($miniUsers)
                {
                    // 更新数据库状态
                    (new MiniAppUser())->where(['uid' => $this->user['id'], 'status' => 0, 'mini_type' => 'WEAPP'])->update(['uid' => 0, 'access_token' => '', 'expires_in' => 0]);
                    // 删除缓存
                    foreach ($miniUsers as $mid)
                    {
                        CacheManage::getInstance()->setCacheConfig('miniapp.user', $mid)->rmCache();
                    }
                }
            } else
            {
                return show(config('code.error'), '至少保留一种登录方式', [], 200);
            }

        }
        catch (\Exception $e)
        {
            return show(config('code.error'), $e->getMessage(), [], 500);
        }
        return show(200, '解绑成功');
    }
}
